package ar.edu.itba.pod.legajo48240.event.threads;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;

import ar.edu.itba.event.EventInformation;
import ar.edu.itba.event.RemoteEventDispatcher;
import ar.edu.itba.node.NodeInformation;
import ar.edu.itba.pod.legajo48240.event.DistributedEventDispatcher;
import ar.edu.itba.pod.legajo48240.model.Host;
import ar.edu.itba.pod.legajo48240.simulation.DistributedSimulationManager;
import ar.edu.itba.pod.legajo48240.utils.Net;
import ar.edu.itba.pod.thread.CleanableThread;

public class PoolNewEventsThread extends CleanableThread {

	private final Host localhost;
	private final DistributedEventDispatcher dispatcher;

	private final static Logger LOGGER = Logger.getLogger(PoolNewEventsThread.class);

	public PoolNewEventsThread(String name, Host localhost, DistributedEventDispatcher dispatcher) {
		super(name);
		this.localhost=localhost;
		this.dispatcher=dispatcher;
	}

	@Override
	public void run() {
		super.run();

		try {
			while(!shouldFinish()){

				sleep(1000*1000);
				LOGGER.info("SEARCHING FOR NEW EVENTS FOR " + localhost.id() );

				try {
					for(NodeInformation node: localhost.network().connectedNodes()){
						if(!localhost.node().equals(node)){
							try {
								RemoteEventDispatcher dispatcher=Net.getDispatcher(node.host(), node.port());
								
								Set<EventInformation> events=dispatcher.newEventsFor(localhost.node());
								if(!events.isEmpty()){
									LOGGER.info("NEW events for" + localhost.node().id() + " from: " + node.id());
									for(EventInformation e: events){
										localhost.dispatcher().publish(e);
									}
								}else{
									LOGGER.info("No new events for" + localhost.node().id() + " from: " + node.id());
								}
							} catch (NotBoundException e) {
								try {
									localhost.network().disconnectFromGroup(node);
								} catch (NotBoundException ignore) {}
							}
						}
					}
				} catch (RemoteException ignore) {}			 // local data
			}
		} catch (InterruptedException ignore) {	
			// TODO: BUG !
			LOGGER.debug("finishing POOL NEW EVENTS FOR THREAD...");
		}

	}
}
